import { Component } from "@angular/core";
import {
  NavController,
  NavParams,
  AlertController,
  ActionSheetController,
  ToastController,
  Platform,
} from "ionic-angular";
import { HttpService } from "../../../providers/http.service";
import { CommonFunc } from "../../../providers/commonFunc";
import { Storage } from "@ionic/storage";
import { SafeControl } from "./bean/safe-control.bean";
import { CameraOptions, Camera } from "@ionic-native/camera";
import { appConfig } from "../../../providers/config";
import { PhotoViewer } from "@ionic-native/photo-viewer";
import {
  FileUploadOptions,
  FileTransferObject,
  FileTransfer
} from "@ionic-native/file-transfer";
import * as moment from "moment";
import { HomePage } from "../../home/home";
import {SafeControlBookPage} from "../safe-control-book/safe-control-book";
import {FileOpener} from "@ionic-native/file-opener";
import {SafeControlDownload} from "./safe-control-download/safe-control-download";

/**
 * 单位安全管理检查
 */
@Component({
  templateUrl: "safe-control.html"
})
export class SafeControlPage {
  private safeControl: SafeControl = new SafeControl();
  appConfig = appConfig;
  userId: any;
  userName: any;
  partyId: any;
  partyOtion: any = [];
  checkRes: any = []; //检查记录结果
  totalResult: any = [];
  pdctId: any; //检查目录id
  pdId: any; //检查计划id
  beCkedPartyName: any;
  beCkedPartyId: any;
  pdType: any;
  checkQuestions: any = [];
  questionList: any = [];
  lawlist:any = [];
  lawContentList: any = [];
  firstLaw:any = [];
  showOrHidden:boolean = false;
  checkUserList: any = [];
  image:string = "assets/icon/bottom.png";
  treatmentMeasures : string = "" ;
  constructor(
    public navCtrl: NavController,
    private alertCtrl: AlertController,
    private httpService: HttpService,
    private navParams: NavParams,
    private commonFunc: CommonFunc,
    private transfer: FileTransfer,
    private storage: Storage,
    private camera: Camera,
    private photoViewer: PhotoViewer,
    private actionSheet: ActionSheetController,
    private toast: ToastController,
    private fileOpener: FileOpener,
    public platform: Platform,
  ) {
    this.totalResult= this.navParams.get("totalResult");
    this.checkRes = this.navParams.get("checkRes"); //检查项结果集
    this.pdctId = this.navParams.get("id"); //
    this.pdId = this.navParams.get("pdId"); //
    this.beCkedPartyName = this.navParams.get("beCkedPartyName"); //被检查单位
    this.beCkedPartyId = this.navParams.get("beCkedPartyId"); //被检查单位id
    this.pdType = this.navParams.get("pdType"); //检查类型
    this.safeControl.usedPartyId = this.beCkedPartyId;
    this.safeControl.usedPartyName = this.beCkedPartyName;
    this.safeControl.checkType = this.pdType;
    this.safeControl.pDetailId = this.pdId;
    this.safeControl.result = this.totalResult;

    this.storage.get("safeControl").then(data=>{
        if (data != null) {
            this.safeControl.checkItem = data.checkItem;
            this.safeControl.dealWay = data.dealWay;
            this.safeControl.dealRemark = data.dealRemark;
            this.safeControl.score = data.score;
            this.safeControl.checkerId = data.checkerId;
            if (this.safeControl.result !=null && this.safeControl.result.length > 0) {
                for (let i = 0; i < this.safeControl.result.length; i++) {
                    for (let j = 0; j < data.result.length; j++) {
                        if (this.safeControl.result[i].pditemid == data.result[j].pditemid && this.safeControl.result[i].result == "0") {
                            this.safeControl.result[i].enforcementCode = data.result[j].enforcementCode;
                        }
                    }
                }
            }
        }
    });

    this.storage.get("user").then(data => {
      this.userId = data.id;
      this.userName = data.userName;
      this.partyId = data.partyId;
      this.safeControl.recorderName = this.userName; //记录人员姓名
      this.safeControl.recorderId = this.userId; //记录人员id
      //检查人员
      this.httpService.queryCheckUser(this.partyId).subscribe(data => {
          if (data.status == "200") {
              let data1 = data.data;
              data1.forEach(data => {
                  if (data.type == "user") {
                      this.checkUserList.push(data);
                  }
              });

          } else {
              console.log("查询失败");
          }
        });
      });

    //法律条文
      this.httpService.queryLaws({}).subscribe(data=>{
          if (data.status == "200") {
           this.lawlist = data.data.list;
          }
      });

    //存在问题
     this.safeControl.state = "1";
     this.checkQuestions = [];
     this.totalResult.forEach(data=>{
          if (data.result == "0") {
              //如果存在问题，默认待整改
              this.safeControl.state = "2";
              this.checkQuestions.push(data);
          }
      });
     //问题预览
      if (this.checkQuestions != null && this.checkQuestions.length > 0){
          for (let i = 0; i <this.checkQuestions.length ; i++) {
              this.questionList.push(this.checkQuestions[i].content +" — 否");
          }
      }

      //存在问题,转化为字符串
      if (this.checkQuestions != null && this.checkQuestions.length > 0) {
          let question = "";
          for (let i = 0; i <this.checkQuestions.length ; i++) {
              if (i == this.checkQuestions.length-1) {
                question =question + this.checkQuestions[i].content + " 否" ;
              }else {
                question =question + this.checkQuestions[i].content + " 否，" ;
              }
          }
          this.safeControl.questions = question;
      }
      //默认检查状态
      if (this.navParams.get("state") == "0") {
          this.safeControl.censorType ="1";
      }
      if (this.navParams.get("state") == "2"){
          this.safeControl.censorType = "2";
      }
  }
    ionViewWillLeave() {
       this.storage.set("safeControl",this.safeControl);
    }
    submit() {
        // this.safeControl.checkerId = this.userId;
        this.safeControl.isSure = "0";
        this.safeControl.checkTimeFrom = this.navParams.get("checkTimeFrom");
        this.safeControl.checkTimeTo = moment(new Date()).format("YYYYMMDDHHmmss");
        /*if (this.safeControl.score) {
            if (this.safeControl.score != "1000") {
                let reg = new RegExp("^[0-9]*$");
                if (
                    !reg.test(this.safeControl.score) ||
                    this.safeControl.score.length > 3
                ) {
                    let tt = this.toast.create({
                        message: "请在打分项输入0-1000数字",
                        duration: 2000,
                        position: "top"
                    });
                    tt.present();
                    return;
                }
            }
        } else {
            let tt = this.toast.create({
                message: "请给使用单位打分",
                duration: 2000,
                position: "top"
            });
            tt.present();
            return;
        }*/
        //判断信息是否输入完整
        if (this.safeControl.checkItem == null ||this.safeControl.checkItem == "" ||
            this.safeControl.dealWay == null ||this.safeControl.dealWay == "" ||
            this.safeControl.state == null || this.safeControl.state == "" ||
            this.safeControl.recorderName ==null ||this.safeControl.recorderName == ""){
            let tt = this.toast.create({
                message: "请选择完整的信息!",
                duration: 2000,
                position: "top"
            });
            tt.present();
            return;
        }
        //校验执法代码映射是否选择完全
        if (this.safeControl.result != null && this.safeControl.result.length > 0) {
            for (let i = 0; i <this.safeControl.result.length ; i++) {
                if (this.safeControl.result[i].result == "0" && this.safeControl.result[i].enforcementCode == null) {
                    let tt = this.toast.create({
                        message: "请选择完整的执法代码映射!",
                        duration: 2000,
                        position: "top"
                    });
                    tt.present();
                    return;
                }
            }
        }

        if (!this.safeControl.recordNameUrl) {
            console.log("maintenanceUserSignId2");
            const alert2 = this.alertCtrl.create({
                // title: '',
                subTitle: "请签名并保存！",
                buttons: ["确定"]
            });
            alert2.present();
            return;
        }
        //法律映射如果多选，法律映射转化字符串
     /*   for (let i = 0; i < this.safeControl.result.length ; i++) {
            if (this.safeControl.result[i] != null && this.safeControl.result[i].enforcementCode!=null
                && this.safeControl.result[i].enforcementCode.length>0){
                let stringCode ="";
                for (let j = 0; j < this.safeControl.result[i].enforcementCode.length ; j++) {
                    if (j == this.safeControl.result[i].enforcementCode.length - 1) {
                        stringCode = stringCode + this.safeControl.result[i].enforcementCode[j] + "";
                    } else {
                        stringCode = stringCode + this.safeControl.result[i].enforcementCode[j] + ",";
                    }
                }
                this.safeControl.result[i].enforcementCode = stringCode;
            }
        }*/
        //选择记录人员
        if (this.checkUserList != null && this.checkUserList.length> 0){
            for (let i = 0; i <this.checkUserList.length ; i++) {
                if (this.checkUserList[i].id == this.safeControl.checkerId) {
                    this.safeControl.checkerName = this.checkUserList[i].userName;
                }
            }
        }

        //违反法律预览
        if (this.lawlist != null && this.lawlist.length > 0) {
            //this.safeControl.state = "2";
            this.lawContentList = [];
            this.treatmentMeasures = "";
            for (let i = 0; i <this.lawlist.length ; i++) {
                if (this.safeControl.result != null && this.safeControl.result.length > 0) {
                    for (let j = 0; j <this.safeControl.result.length ; j++) {
                        if (this.lawlist[i].code == this.safeControl.result[j].enforcementCode) {
                            this.lawContentList.push("第" + this.lawlist[i].lawEnforcementBasis + "条" + this.lawlist[i].lawEnforcementBasisContent);
                            this.treatmentMeasures = this.treatmentMeasures + this.lawlist[i].illegalActivity;
                        }
                    }
                }
            }
        }
        this.safeControl.treatmentMeasures = this.treatmentMeasures;
        // 判断下一步操作
        let label = "";
        switch (this.safeControl.dealWay) {
            case "1":
                label = "下达监察指令书";
                break;
            case "2":
                label = "实施查封";
                break;
            case "3":
                label = "实施扣押";
                break;
            case "4":
                label = "其他";
                break;
            default:
                break;
        }
        let alert = this.alertCtrl.create();
        if (this.safeControl.dealWay == "1") {
            alert.setTitle("");
            alert.setSubTitle("您选择了以下处理措施，是否现在填写？");
            alert.addInput({
                type: "radio",
                label: label,
                value: this.safeControl.dealWay,
                checked: true
            });
            alert.addButton({
                text: "是",
                //根据data类型 判断要跳转的页面
                handler: data => {
                    window["jQuery"]("#signatureid").remove();
                    window["jQuery"]("#showImage").remove();
                    this.navCtrl.push(SafeControlBookPage, {
                        questionList: this.questionList,
                        lawContentList: this.lawContentList,
                        safeControl: this.safeControl,
                        treatmentMeasures:this.treatmentMeasures
                    });
                },
            });

            alert.addButton({
                text: "否",
                handler: () => {
                    //提交
                    this.httpService.addSafeControlRecord(this.safeControl).subscribe(data1 => {
                        if (data1.status == 200) {
                            window["jQuery"]("#signatureid").remove();
                            window["jQuery"]("#showImage").remove();
                            //提交成功后清空缓存信息
                            this.removeStorage();

                            let tt = this.toast.create({
                                message: "提交成功",
                                duration: 2000,
                                position: "top"
                            });
                            // tt.present().then(() => {
                            //     this.navCtrl.setRoot(HomePage).then(() => {
                            //         window["jQuery"]("#signatureid").remove();
                            //         window["jQuery"]("#showImage").remove();
                            //         this.navCtrl
                            //             .getActive()
                            //             .getNav()
                            //             .remove(0);
                            //     });
                            // });
                            // this.isDownloadFileAndSave(data1.data);
                            this.navCtrl.push(SafeControlDownload, {data : data1.data});
                        } else {
                            const alert = this.alertCtrl.create({
                                subTitle: "信息保存失败",
                                buttons: ["确定"]
                            });
                            alert.present();
                        }
                    })
                }
            });
            alert.present();
        }else {
            this.httpService.addSafeControlRecord(this.safeControl).subscribe(data1 => {
                if (data1.status == 200) {
                    let tt = this.toast.create({
                        message: "提交成功",
                        duration: 2000,
                        position: "top"
                    });
                    tt.present();
                       /* this.navCtrl.setRoot(HomePage).then(() => {
                            window["jQuery"]("#signatureid").remove();
                            window["jQuery"]("#showImage").remove();
                            this.navCtrl
                                .getActive()
                                .getNav()
                                .remove(0);
                        });*/
                    window["jQuery"]("#signatureid").remove();
                    window["jQuery"]("#showImage").remove();
                    //提交成功后清空缓存信息
                    this.removeStorage();
                    this.navCtrl.push(SafeControlDownload, {data : data1.data});
                } else {
                    const alert = this.alertCtrl.create({
                        subTitle: "信息保存失败",
                        buttons: ["确定"]
                    });
                    alert.present();
                }
            })
        }
    }

    /**
     * 添加是否下载文件，并存储到本地
     *
     */
    isDownloadFileAndSave(data){
        let alert = this.alertCtrl.create();
        alert.setTitle("");
        alert.setSubTitle("是否下载监督检查记录文件？");
        alert.addButton({
            text: "是",
            //根据data类型 判断要跳转的页面
            handler: () => {
                //下载文件。
                if(data.inspectionRecordsDoc){
                    this.download( data.inspectionRecordsDoc.split(",")[0]);
                }else{
                    this.navCtrl.push(HomePage, {});
                }
            },
        });

        alert.addButton({
            text: "否",
            handler: () => {
                this.navCtrl.push(HomePage, {});
            }
        });
        alert.present();
    }

    /**
     * 下载文件
     * @param fileName
     */
    download(fileName) {
        const fileTransfer: FileTransferObject = this.transfer.create();
        fileTransfer.download(appConfig+fileName, fileName).then((entry) => {
            console.log('download complete: ' + entry.toURL());
            this.fileOpener.open(entry.nativeURL, this.getFileMimeType(this.getFileType(fileName)))
                .then(() => {
                    console.log('打开成功');
                })
                .catch(() => {
                    console.log('打开失败');
                });
        }, (error) => {
            console.log('download fail..')
        });
    }


  doCamera(i) {
    let options: CameraOptions = {
      quality: 85, // destinationType: this.camera.DestinationType.DATA_URL,
      // encodingType: this.camera.EncodingType.JPEG,
      mediaType: this.camera.MediaType.PICTURE,
      targetWidth: 1500,
      targetHeight: 1500,
      correctOrientation: true
    };
    this.camera.getPicture(options).then(
      imageData => {
        const options: FileUploadOptions = {};
        let serverUrl = encodeURI(appConfig.IP_URL + appConfig.API.upload);
        options.fileKey = "file";
        options.fileName = "test.jpg";
        options.mimeType = "image/jpeg";
        const fileTransfer: FileTransferObject = this.transfer.create();
        fileTransfer.upload(imageData, serverUrl, options).then(restul => {
          let aa = JSON.parse(restul["response"]);
          if (aa["status"] == 200) {
            if (aa["data"].length > 0) {
              if (i == "c") {
                this.safeControl.questionsUrls.push(aa["data"]);
              } else {
                this.safeControl.questionsUrls[i] = aa["data"];
              }
            }
          }
        });
      },
      err => {
        // Handle error
      }
    );
  }

  showQuestions() {
      if (this.safeControl.result.length > 0) {
          this.showOrHidden = !this.showOrHidden;
      }else {
          this.showOrHidden = false;
      }
  }

  onHold(param) {
    let actionSheet = this.actionSheet.create({
      buttons: [
        {
          text: "重拍",
          role: "重拍",
          handler: () => {
            let i = this.safeControl.questionsUrls.indexOf(param);
            this.doCamera(i);
          }
        },
        {
          text: "查看大图",
          role: "查看大图",
          handler: () => {
            let url: string = param;
            this.photoViewer.show(
              encodeURI(
                this.appConfig.IP_URL + this.appConfig.API.getUpload + url
              ).replace("%5C", "/"),
              null,
              { share: false }
            );
          }
        },
        {
          text: "删除",
          handler: () => {
            let i = this.safeControl.questionsUrls.indexOf(param);
            this.safeControl.questionsUrls.splice(i, 1);
          }
        },
        {
          text: "取消",
          role: "取消",
          handler: () => {
            //console.log('Cancel clicked');
          }
        }
      ]
    });
    actionSheet.present();
  }

    getImgUrl(param) {
        this.safeControl.recordNameUrl = param.imageDate;
    }


    getFileType(fileName : string){
        return fileName.substring(fileName.lastIndexOf('.') + 1, fileName.length).toLowerCase();
    }

    getFileMimeType(fileType : string){
        let mimeType: string = '';

        switch (fileType) {
            case 'txt':
                mimeType = 'text/plain';
                break;
            case 'docx':
                mimeType = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
                break;
            case 'doc':
                mimeType = 'application/msword';
                break;
            case 'pptx':
                mimeType = 'application/vnd.openxmlformats-officedocument.presentationml.presentation';
                break;
            case 'ppt':
                mimeType = 'application/vnd.ms-powerpoint';
                break;
            case 'xlsx':
                mimeType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
                break;
            case 'xls':
                mimeType = 'application/vnd.ms-excel';
                break;
            case 'zip':
                mimeType = 'application/x-zip-compressed';
                break;
            case 'rar':
                mimeType = 'application/octet-stream';
                break;
            case 'pdf':
                mimeType = 'application/pdf';
                break;
            case 'jpg':
                mimeType = 'image/jpeg';
                break;
            case 'png':
                mimeType = 'image/png';
                break;
            default:
                mimeType = 'application/' + fileType;
                break;
        }
        return mimeType;
    }

    //
    removeStorage(){
        this.storage.remove("producePartyResult");
        this.storage.remove("userPartyResult");
        this.storage.remove("elevatorResult");
        this.storage.remove("checkPartyResult");
        this.storage.remove("defineResult");
        this.storage.remove("producePartyStatus");
        this.storage.remove("userPartyStatus");
        this.storage.remove("elevatorStatus");
        this.storage.remove("checkPartyStatus");
        this.storage.remove("definedStatus");
        this.storage.remove("elevatorTotalResult");
        this.storage.remove("safeControl");
        this.storage.remove("safeControl2");
    }
}
